package com.ys.web.user.friends.controller;

import com.ys.base.BaseConstants;
import com.ys.base.EnumType;
import com.ys.utils.base.http.McodeHandler;
import com.ys.utils.base.http.ResponseHandler;
import com.ys.utils.base.j2se.JsonUtil;
import com.ys.utils.base.j2se.StringHandler;
import com.ys.utils.base.secret.MD5;
import com.ys.utils.help.UserUtils;
import com.ys.utils.redis.Redis;
import com.ys.utils.redis.key.UserKey;
import com.ys.utils.spring.config.SystemError;
import com.ys.utils.spring.properties.Config;
import com.ys.web.user.friends.dto.FriendsRemarkDTO;
import com.ys.web.user.friends.manager.FriendsManager;
import com.ys.web.user.friends.po.BaseUserApplyPO;
import com.ys.web.user.friends.po.BaseUserFriendsPO;
import com.ys.web.user.friends.service.FriendsService;
import com.ys.web.user.login.LoginInfo;
import com.ys.web.user.login.LoginService;
import com.ys.web.user.privacy.Privacy;
import com.ys.web.user.privacy.PrivacyManager;
import com.ys.web.user.privacy.PrivacyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName FriendsController
 * @Description 好友系列接口
 * @Author qxj
 * @Date 2021/5/9 9:37
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/friends")
public class FriendsController {

    @Autowired
    private FriendsService friendsService;
    @Autowired
    private LoginService loginService;
    @Autowired
    private PrivacyService privacyService;

    /**
     * @title queryFriendsByPhone
     * @description 通过电话号码获取好友信息
     * @author qxj
     * @updateTime 2021/5/9 10:18
     * @return: java.lang.String
     */
    @PostMapping("/queryFriendsByPhone")
    public String queryFriendsByPhone(@RequestAttribute String uid, String key) {
        UserUtils.validateUserAccountStatus(uid);
        LoginInfo loginInfo = loginService.infoByPhone(key);
        if (loginInfo == null) {
            return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "用户不存在");
        }
        //用户屏蔽手机号搜索直接返回
        if (PrivacyManager.hidePhone(StringHandler.getLong(loginInfo.getId()))) {
            return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "用户不存在");
        }
        if (StringHandler.isNotEmpty(loginInfo)) {
            if (loginInfo.getId().equals(uid)) {
                SystemError.wrapBs("500", "您不能添加自己到通讯录");
            }
            String str = (String) Redis.hash.hGet(UserKey.getUserFriendsListKey(uid), loginInfo.getId());
            if (StringHandler.isNotEmpty(str)) {
                BaseUserFriendsPO baseUserFriendsPO = JsonUtil.jsonToBean(str, BaseUserFriendsPO.class);
                if (baseUserFriendsPO.getId() != null && !"null".equals(baseUserFriendsPO.getFriendId())) {
                    loginInfo.setFriendId(McodeHandler.to32Radix(Long.parseLong(loginInfo.getId())));
                    loginInfo.setFriendRemark(baseUserFriendsPO.getFriendRemark());
                    loginInfo.setFriendDesc(baseUserFriendsPO.getFriendDesc());
                }
            }
            loginInfo.setId(McodeHandler.to32Radix(Long.parseLong(loginInfo.getId())));

            loginInfo.setPhone("");
            loginInfo.setPassword("");
            loginInfo.setSalt("");
            loginInfo.setRealName("");
            loginInfo.setRealIdCard("");
            loginInfo.setAppId("");
            loginInfo.setOpenId("");
            loginInfo.setUnionId("");
            loginInfo.setAppleId("");
            loginInfo.setPayPass("");

        }
        if(uid.equals(StringHandler.getString(BaseConstants.ClientConstants.CLIENT_ID))){
            loginInfo.setFriendId(loginInfo.getId());
        }
        return ResponseHandler.success(loginInfo);
    }

    /**
     * @title queryFriendsByAlias
     * @description 通过用户标识获取好友信息
     * @author qxj
     * @updateTime 2021/5/9 10:18
     * @return: java.lang.String
     */
    @PostMapping("/queryFriendsByAlias")
    public String queryFriendsByAlias(@RequestAttribute String uid, String friendId) {
        UserUtils.validateUserAccountStatus(uid);
        if (!Boolean.parseBoolean(Config.pp.get("friends.alias.query"))) {
            SystemError.wrapBs("500", "用户不存在...");
        }
        long friend = McodeHandler.from32Radix(friendId);
        //用户屏蔽手机号搜索直接返回
        if (PrivacyManager.hideQrcode(friend)) {
            return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "用户不存在");
        }
        LoginInfo loginInfo = loginService.infoByUid(StringHandler.getString(friend));
        if (StringHandler.isNotEmpty(loginInfo)) {
            String key = UserKey.getUserFriendsListKey(uid);
            String str = (String) Redis.hash.hGet(key, loginInfo.getId());
            if (StringHandler.isNotEmpty(str)) {
                BaseUserFriendsPO baseUserFriendsPO = JsonUtil.jsonToBean(str, BaseUserFriendsPO.class);
                if (StringHandler.isNotEmpty(baseUserFriendsPO.getUserId()) && !"null".equals(baseUserFriendsPO.getUserId())) {
                    loginInfo.setFriendId(McodeHandler.to32Radix(Long.parseLong(loginInfo.getId())));
                    loginInfo.setFriendRemark(baseUserFriendsPO.getFriendRemark());
                    loginInfo.setFriendDesc(baseUserFriendsPO.getFriendDesc());


                    //如果数据不一致   统一数据
                    if (!loginInfo.getNickName().equals(baseUserFriendsPO.getNickName()) || !loginInfo.getAvatarUrl().equals(baseUserFriendsPO.getAvatarUrl())) {
                        loginInfo.setNickName(baseUserFriendsPO.getNickName());
                        loginInfo.setAvatarUrl(baseUserFriendsPO.getAvatarUrl());

                        Redis.hash.hSet(key, baseUserFriendsPO.getFriendId(), JsonUtil.toJson(baseUserFriendsPO));
                    }
                }
            }
            loginInfo.setId(McodeHandler.to32Radix(Long.parseLong(loginInfo.getId())));

            loginInfo.setPhone("");
            loginInfo.setPassword("");
            loginInfo.setSalt("");
            loginInfo.setRealName("");
            loginInfo.setRealIdCard("");
            loginInfo.setAppId("");
            loginInfo.setOpenId("");
            loginInfo.setUnionId("");
            loginInfo.setAppleId("");
            loginInfo.setPayPass("");
        }
        return ResponseHandler.success(loginInfo);
    }

    /***
     * @title addFriendsById
     * @description 根据好友id 添加好友
     * @author qxj
     * @updateTime 2021/5/9 16:39
     * @return: java.lang.String
     */
    @PostMapping("/addFriendsById")
    public String addFriendsById(@RequestAttribute String uid, String friendId, @RequestParam(defaultValue = "0") int groupId, String remark,String addKey) {
        //判断用户是否是群管理
//        if(!friendsService.groupManager(uid)){
//            int userFriendNumber = friendsService.userFriendNumber(uid);
//            int user_apply = friendsService.userApplyNumber(uid);
//            int number = userFriendNumber+user_apply;
//            //判断用户好友是否大于2
//            if(number>StringHandler.getInt(Config.pp.get("ys.user.friend.max.number"),2)){
//                SystemError.wrapBs("500", "系统异常..");
//            }
//
//        }
        if (!Boolean.parseBoolean(Config.pp.get("friends.alias.add"))) {
            SystemError.wrapBs("500", "用户不存在...");
        }
        if(StringHandler.isEmpty(addKey)){
            SystemError.wrapBs("500", "用户不存在..");
        }
        String md5Str = Config.pp.get("friends.add.friends.by.id.md5.str");
        String md5Key = MD5.MD5(McodeHandler.to32Radix(StringHandler.getLong(uid))+friendId+md5Str);
        if(!addKey.equals(md5Key)){
            SystemError.wrapBs("500", "用户不存在....");
        }
        UserUtils.validateUserAccountStatus(uid);
        friendId = String.valueOf(McodeHandler.from32Radix(friendId));
        if (uid.equals(friendId)) {
            return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "不能添加自己为好友");
        }
        String key = UserKey.addFriendKey((StringHandler.getLong(uid) + StringHandler.getLong(friendId)));
        boolean lock = Redis.str.setNX(key);
        if (lock) {
            friendsService.addFriendsById(uid, friendId, groupId, remark);
            Redis.key.del(key);
        } else {
            Redis.key.del(key);
            return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "请稍后再操作");
        }
        return ResponseHandler.success();
    }

    @PostMapping("/addFriendsByPhone")
    public String addFriendsByPhone(@RequestAttribute String uid, String phone, @RequestParam(defaultValue = "0") int groupId, String remark) {
        //判断用户是否是群管理
//        if(!friendsService.groupManager(uid)){
//            int userFriendNumber = friendsService.userFriendNumber(uid);
//            int user_apply = friendsService.userApplyNumber(uid);
//            int number = userFriendNumber+user_apply;
//            //判断用户好友是否大于2
//            if(number>StringHandler.getInt(Config.pp.get("ys.user.friend.max.number"),2)){
//                SystemError.wrapBs("500", "系统异常..");
//            }
//
//        }
        UserUtils.validateUserAccountStatus(uid);
        LoginInfo loginInfo = loginService.infoByPhone(phone);
        if(StringHandler.isEmpty(loginInfo)){
            return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "添加好友信息错误");
        }
        if (uid.equals(loginInfo.id)) {
            return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "不能添加自己为好友");
        }
        String key = UserKey.addFriendKey((StringHandler.getLong(uid) + StringHandler.getLong(loginInfo.id)));
        boolean lock = Redis.str.setNX(key);
        if (lock) {
            friendsService.addFriendsById(uid, loginInfo.id, groupId, remark);
            Redis.key.del(key);
        } else {
            Redis.key.del(key);
            return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "请稍后再操作");
        }
        return ResponseHandler.success();
    }

    /***
     * @title delFriendsById
     * @description
     * @author qxj * @param uid
     * @param friendId 好友id
     * @param uid 用户id
     * @updateTime 2021/5/9 16:58
     * @return: java.lang.String
     */
    @PostMapping("/delFriendsById")
    public String delFriendsById(@RequestAttribute String uid, String friendId) {
        UserUtils.validateUserAccountStatus(uid);
        friendId = String.valueOf(McodeHandler.from32Radix(friendId));
        return friendsService.delFriendsById(uid, friendId) > 0
                ? ResponseHandler.success() : ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), EnumType.ResponseCode.Fail.getDesc());
    }

    /***
     * @title setFriendsRemarkInfo
     * @description
     * @author qxj
     * @param friendsRemarkDTO 好友备注信息DTO
     * @updateTime 2021/5/9 17:24
     * @return: java.lang.String
     */
    @PostMapping("/setFriendsRemarkInfo")
    public String setFriendsRemarkInfo(@Validated FriendsRemarkDTO friendsRemarkDTO,
                                       @RequestAttribute String uid) {
        friendsRemarkDTO.setFriendId(String.valueOf(McodeHandler.from32Radix(friendsRemarkDTO.getFriendId())));
        return friendsService.setFriendsRemarkInfo(uid, friendsRemarkDTO) > 0
                ? ResponseHandler.success() : ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), EnumType.ResponseCode.Fail.getDesc());
    }

    /**
     * @param uid    用户id
     * @param userId 好友id
     * @title getFriendsDetailByUserId
     * @description 获取用户详情
     * @author qxj
     * @updateTime 2021/5/9 17:32
     * @return: java.lang.String
     */
    @PostMapping("/getFriendsDetailByUserId")
    public String getFriendsDetailByUserId(@RequestAttribute String uid, String userId) {
        userId = String.valueOf(McodeHandler.from32Radix(userId));
        BaseUserFriendsPO obj = friendsService.getFriendsDetailByUserId(uid, userId);
        return obj != null ? ResponseHandler.success(obj) : ResponseHandler.error("6001", "您与对方目前不是好友");
    }

    /**
     * @param uid 用户id
     * @title getFriendsList
     * @description 获取好友列表
     * @author quxinjun
     * @updateTime 2021/5/10 9:24
     * @return: java.lang.String
     */
    @PostMapping("/getFriendsList")
    public String getFriendsList(@RequestAttribute String uid, @RequestParam("searchKey") String searchKey) {
        LoginInfo loginInfo = loginService.infoByUid(uid);
        if(StringHandler.isNotEmpty(loginInfo)){
            loginInfo.checkStatus();
        }
        List<BaseUserFriendsPO> friendsList = friendsService.getFriendsList(uid, searchKey);
        List<BaseUserFriendsPO> list = new ArrayList<>();
        list.add(UserUtils.CLIENT);
        list.addAll(friendsList);
        return ResponseHandler.list(list);
    }

    /**
     * @param uid    用户id
     * @param fromId 发起人id
     * @title agreeApply
     * @description
     * @author qxj
     * @updateTime 2021/5/10 22:10
     * @return: java.lang.String
     */
    @PostMapping("/agreeApply")
    public String agreeApply(@RequestAttribute String uid, String fromId) {
        UserUtils.validateUserAccountStatus(uid);
        fromId = String.valueOf(McodeHandler.from32Radix(fromId));
        return friendsService.agreeApply(uid, fromId) > 0
                ? ResponseHandler.success() : ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), EnumType.ResponseCode.Fail.getDesc());
    }

    /**
     * @param uid 用户id
     * @title getApplyList
     * @description 获取申请列表
     * @author qxj
     * @updateTime 2021/5/10 22:36
     * @return: java.lang.String
     */
    @PostMapping("/getApplyList")
    public String getApplyList(@RequestAttribute String uid) {
        List<BaseUserApplyPO> applyList = friendsService.getApplyList(uid);
        return ResponseHandler.list(applyList);
    }

    /**
     * 好友黑名单
     *
     * @param uid      操作人uid
     * @param friendId 还有alias
     * @param type     操作类型  1拉黑 2移出黑名单
     * @return
     */
    @PostMapping("/friendBlack")
    public String friendBlack(@RequestAttribute String uid, String friendId, int type) {
        friendsService.friendBlack(uid, McodeHandler.from32Radix(friendId), type);
        return ResponseHandler.success();
    }

    /**
     * 黑名单列表
     *
     * @param uid 操作人uid
     * @return
     */
    @PostMapping("/friendBlackList")
    public String friendBlackList(@RequestAttribute String uid) {
        List<Long> list = FriendsManager.getBlackFriendsId(uid);
        if (StringHandler.isEmpty(list)) {
            return ResponseHandler.list(new ArrayList<>());
        }
        List<Map<String, Object>> data = list.stream().map(StringHandler::getString).map(x -> {
            LoginInfo loginInfo = loginService.infoByUid(x);
            Map<String, Object> loginUser = new HashMap<>();
            String alias = McodeHandler.to32Radix(StringHandler.getLong(loginInfo.getId()));
            loginUser.put("friendId", alias);
            loginUser.put("nickName", loginInfo.getNickName());
            loginUser.put("avatarUrl", loginInfo.getAvatarUrl());
            return loginUser;
        }).collect(Collectors.toList());
        return ResponseHandler.list(data);
    }


    /**
     * @param uid      操作用户id
     * @param groupId  群组id
     * @param friendId 好友id
     * @title setDisturb
     * @description 设置消息免打扰
     * @author quxinjun
     * @updateTime 2021/6/9 17:51
     * @return: java.lang.String
     */
    @PostMapping("/setDisturb")
    public String setDisturb(@RequestAttribute Long uid, String friendId, String groupId) {
        friendsService.setDisturb(uid, friendId, groupId);
        return ResponseHandler.success();
    }


    @PostMapping("/delApplyById")
    public String delApplyById(@RequestAttribute String uid, String applyId) {
        if (StringHandler.isEmpty(applyId)) {
            return ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), "参数传递错误");
        }
        return friendsService.delApplyById(uid, applyId) > 0
                ? ResponseHandler.success() : ResponseHandler.error(EnumType.ResponseCode.Fail.getCode(), EnumType.ResponseCode.Fail.getDesc());
    }
    @PostMapping("/copy")
    public String copyFriends(@RequestAttribute String uid, String friendsCode) {
        if (StringHandler.isEmpty(friendsCode)) {
            SystemError.wrapBs("500", "好友id不能为空");
        }
        Privacy privacy = privacyService.getPrivacyById(StringHandler.getLong(uid));
        if(StringHandler.isEmpty(privacy)){
            SystemError.wrapBs("500", "当前用户未开启好友复制");
        }
        if(!privacy.friendsCopy){
            SystemError.wrapBs("500", "当前用户未开启好友复制！");
        }
        long friendsId = 0l;
        try {
            friendsId = McodeHandler.from32Radix(friendsCode.toUpperCase());
        } catch (Exception e) {
            SystemError.wrapBs("-1", "邀请码有误");
        }
        LoginInfo frinendsInfo = loginService.infoByUid(friendsId+"");
        if (StringHandler.isEmpty(frinendsInfo)) {
            SystemError.wrapBs("500", "好友信息错误");
        }
        if (frinendsInfo.getAccountStatus()!=0 ) {
            SystemError.wrapBs("500", "好友信息错误！");
        }
        friendsService.copyFriends(uid,friendsId);
        return ResponseHandler.success();
    }

}
